// pages/phySearch/index.wxml.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
const app = getApp()
const cacheDateKey = 'today_is_login'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLogin: (wx.getStorageSync('isLogin') && wx.getStorageSync('user_phone')) ? true : false,
        loginsrc: '',
        huaweilogin: '',
        theme: '',
        wode: '',
        indexpng: '',
        gypng: '',
        isChooseProtocal: false,
        minDate: '1940-01-01',
        date: '1980-01-01',
        endDate: '',
        birthTime: 0,
        array: ['23点~1点', '1点~3点', '3点~5点', '5点~7点', '7点~9点', '9点~11点', '11点~13点', '13点~15点', '15点~17点', '17点~19点', '19点~21点', '21点~23点'],
        zifei: 0,
        freeTimes: 0,
        isFree: 0,
        ffbtn: '',
        mfbtn: '',
        admf: '',
        audit: 0,
        payShow: false,
        // 体质查询结果, 几个相关字段
        year_end: '',
        zodiac: '',
        month_day: '',
        detail_time: '',
        medicine_btn: true,
        respData: '',
        // 选择出生地. 出生省份, 与服务端 config.app.area_info保持一致
        birthPlaceArray: ['云南省', '河南省', '湖北省', '湖南省', '山东省', '江苏省', '安徽省', '上海市', '浙江省', '江西省', '福建省', '台湾省', '重庆市', '贵州省', '四川省', '广东省', '黑龙江省', '吉林省', '辽宁省', '北京市', '天津市', '河北省', '山西省', '陕西省', '甘肃省', '青海省', '香港特别行政区', '、澳门特别行政区', '海南省', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', '内蒙古自治区'],
        selectedOption: '请选择出生省份',
        pickerValue: 0,
        showPickerFlag: false,
        // 是否隐藏 诊断&看广告&单次付费的按钮
        handOver: false,
        activeNames: [],
        predictResData: [],
        isPredict: false,
        formattedDate: '',
        aiResponse: ''             
    },
    onPredictFutureChange(event) {
        this.setData({
            isPredict: event.detail,
        });
    },    
    onCollapseChange(event) {
        // 折叠栏切换事件
        this.setData({
            activeNames: event.detail,
        });
    },
    // 控制下拉框
    showPicker() {
        this.setData({
            showPickerFlag: true // 点击时显示 picker
        });
    },
    onCancel() {
        this.setData({
            showPickerFlag: false // 取消时隐藏 picker
        });
    },
    onConfirm(event) {
        const index = event.detail.value; // 获取选中的索引
        this.setData({
            showPickerFlag: false,
            selectedOption: index
        });
    },
    /**
     * 单次付费
     */
    oncePay: function () {
        let that = this;
        let cacheUserInfo = wx.getStorageSync('user_phone');
        let user_phone = (cacheUserInfo.phoneNumber && typeof (cacheUserInfo.phoneNumber) != 'undefined') ? cacheUserInfo.phoneNumber : '';

        wx.request({
            url: app.globalData.domain + 'v3/index/intoOrder',
            data: {
                type: 7,
                combo_type: 0,
                user_phone: user_phone
            },
            success: function (res) {
                console.log(res)
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
                // 发起支付
                wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    package: res.data.data.package,
                    signType: res.data.data.signType,
                    paySign: res.data.data.paySign,
                    success(res) {
                        console.log('debug支付成功')
                        that.gotoPredict()
                    },
                    fail(res) {
                        wx.showModal({
                            title: '温馨提示',
                            showCancel: false,
                            content: '支付失败!'
                        })
                        return;
                    }
                })
            }
        })        
    }, 
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 未授权的先进行授权
        let isChooseProtocal = wx.getStorageSync('isChooseProtocal') ? wx.getStorageSync('isChooseProtocal') : false;
        //变量赋值
        this.setData({
            isChooseProtocal: isChooseProtocal,
        });
        // 授权
        if (!isChooseProtocal) {
            wx.setStorageSync('toMenu', '/pages/phySearch/index');
            this.toLogin();
        }       
        // 初始化日期
        let newday = new Date();
        let endDate = [newday.getFullYear(), (newday.getMonth() + 1 < 10 ? '0' : '') + (newday.getMonth() + 1), (newday.getDate() < 10 ? '0' : '') + newday.getDate()].join('-');

        this.setData({
            endDate: endDate
        });
    },

    onShow() {
        if (wx.getStorageSync('theme') == 'style1') {
            this.setData({
                theme: 'style1',
                loginsrc: 'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png',
                huaweilogin: 'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png',
                ffbtn: 'https://aiw.oss-cn-beijing.aliyuncs.com/year/Group15.png',
                admf: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/admf2.png',
                mfbtn: 'https://aiw.oss-cn-beijing.aliyuncs.com/year/Group16.png',
                wode: '/images/wodepng.png',
                indexpng: '/images/indexpng.png',
                gypng: '/images/gypng.png'
            })
        } else {
            this.setData({
                theme: 'init',
                loginsrc: 'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png',
                huaweilogin: 'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png',
                ffbtn: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/-s-ks_ff.png',
                admf: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/admf1.png',
                mfbtn: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/ks_mf@2x.png',
                wode: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/tab_me_n@2x.png',
                indexpng: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/tab_home_s@2x.png',
                gypng: '/images/ai.png'
            })
        }

        this.setData({
            isLogin: (wx.getStorageSync('isLogin') && wx.getStorageSync('user_phone'))
        })
        // 服务端返回的可否免费使用的标志
        const usedDay = wx.getStorageSync('used_day');

        if (usedDay == 200) {
            this.setData({
                isFree: 1
            });            
        }

        setTimeout(() => {
            app.show(this, 'show', 1)
        }, 1000);
    },
    // 转至登陆授权页面
    toLogin() {
        wx.redirectTo({
            url: '/pages/login/index',
        })
    },
    // 转至个人中心
    toMe() {
        wx.navigateTo({
            url: '/pages/personal/me',
        })
    },
    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            date: e.detail.value
        })
    },
    bindPickerChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            birthTime: e.detail.value
        })
    },

    getPhoneNumber1(e) {
        let {
            encryptedData,
            iv,
            code
        } = e.detail
        // 如果授权获取手机号则进入下个页面 
        if (code) {
            this.getPhone(code, 1)
        } else {
            Dialog.alert({
                title: '温馨提示',
                message: '请授权登录',
                theme: 'round-button',
            }).then(() => {
                // on close
            });
        }
    },
    getPhoneNumber(e) {
        console.log(e);
        let {
            encryptedData,
            iv,
            code
        } = e.detail
        // 如果授权获取手机号则进入下个页面 
        if (code) {
            this.getPhone(code, 1)
        } else {
            Dialog.alert({
                title: '温馨提示',
                message: '请授权登录',
                theme: 'round-button',
            }).then(() => {});
        }
    },
    // 具体执行获取手机号， 与服务端交互
    getPhone(code, type) {
        let that = this
        var reqUri = app.globalData.domain + 'index/index/getUserWxPhone';
        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                code,
            },
            success(res) {
                if (res.data.code == app.globalData.successCode) {
                    let {
                        phoneNumber
                    } = res.data.data
                    // 将用户的 手机号缓存
                    wx.setStorageSync('user_phone', res.data.data)
                    that.login(phoneNumber, type)
                } else {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
            }
        })
    },
    /**
     * 执行用户 使用手机号 登陆过程
     */
    login(phone, type) {
        let that = this
        let reqUri = app.globalData.domain + 'index/index/doReg';

        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                phone,
                types: 'mini',
                openid: app.globalData.openId,
                agentId: wx.getStorageSync('agentId') ?? 1,
                hasTizhiQualify: wx.getStorageSync('hasTizhiQualify') ?? 0
            },
            success(res) {
                console.log(res)
                if (res.data.code == app.globalData.successCode) {
                    if (type == 1) {
                        wx.setStorageSync('isLogin', true)
                        that.setData({
                            isLogin: wx.getStorageSync('isLogin'),
                        })
                        let cacheUserInfo = wx.getStorageSync('user_phone');
                        let user_phone = (cacheUserInfo.phoneNumber && typeof (cacheUserInfo.phoneNumber) != 'undefined') ? cacheUserInfo.phoneNumber : ''
                        let res = wx.getSystemInfoSync();
                        let isIos = 0;
                        if (res.platform == 'ios') {
                            isIos = 1;
                        }
                        wx.request({
                            url: app.globalData.domain + 'v4/index/getUserIsUse',
                            data: {
                                user_phone: user_phone,
                                isIos: isIos
                            },
                            success(res) {
                                console.log('getUserIsUse接口--:' + res.data.data)
                                if (res.data.code == 0) {
                                    that.setData({
                                        zifei: res.data.data.zifei,
                                        freeTimes: res.data.data.times,
                                        // isFree: res.data.data.is_used,
                                        combo_type: res.data.data.combo_type,
                                        combo_type2: res.data.data.combo_type2,
                                        audit: res.data.data.audit
                                    });
                                    // that.showCombo()
                                }
                            }
                        })
                    } else {
                        Toast.success('登录成功,即将跳转')
                        wx.setStorageSync('isLogin', true)
                        wx.redirectTo({
                            url: '/pages/personal/me',
                        })
                    }

                } else {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
            }
        })
    },
    /**
     * 展示套餐
     */
    showCombo: function () {
        this.setData({
            payShow: true
        });
    },

    /**
     * 免费体验的测试
     */
    toFreeLoading: function () {
        let that = this
        // 传递 出生年月日&&时间. 获取服务端数据

    },
    toHome: function () {
        wx.navigateTo({
            url: '/pages/menu/index',
        })
    },
    // 去健康咨询板块
    goMedical: function () {
        wx.navigateTo({
            url: '/pages/newDetail/indexV2?type=1-1-5&cid3=19',
        })
    },
    // 体检预测
    gotoPredict () {
        let that = this;
        let cacheUserInfo = wx.getStorageSync('user_phone');
        let user_phone = (cacheUserInfo.phoneNumber && typeof (cacheUserInfo.phoneNumber) != 'undefined') ? cacheUserInfo.phoneNumber : '';
        wx.request({
            url: app.globalData.domain + 'v4/index/getTizhiSearch',
            method: 'POST',
            data: {
                isPredict: that.data.isPredict,
                user_phone: user_phone,
                type: 1,
                date: that.data.date,
                birthTime: that.data.birthTime,
                birthPlace: that.data.selectedOption,
                usedDay: wx.getStorageSync('used_day')
            },
            success: function (res) {
                console.log(res)
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                } else {
                    const { year_end, zodiac, month_day, animal_ill, birth_place_description, detail_time } = res.data.data;
                    let response = `以下内容经过国家网信办备案的SpaceTime天纪云深度合成算法深度思考：\n`;
                    // 检查每个变量是否为空，如果不为空则拼接到 response 中
                    if (year_end) response += `- ${year_end} \n`;
                    if (zodiac) response += `- ${zodiac} \n`;
                    if (month_day) response += `- ${month_day} \n`;
                    if (animal_ill) response += `- ${animal_ill} \n`;
                    if (birth_place_description) response += `- ${birth_place_description} \n`;
                    if (detail_time) response += `- ${detail_time} \n`;
                    // 处理每个对象
                    if (res.data.data.predict_res.predictRes && typeof res.data.data.predict_res.predictRes === "object") {
                        const results = res.data.data.predict_res.predictRes.map(item => {
                            // 拼接 five_yun, six_qi, six_tizhi, tizhi_and_tiangan
                            const firstLine = `${item.predict_year}年 \n ${item.five_yun} ${item.six_qi} ${item.six_tizhi} ${item.tizhi_and_tiangan}`;
                            // 处理 month 对象
                            let monthLines = "";
                            if (item.month && typeof item.month === "object" && !Array.isArray(item.month)) {
                                // 遍历 month 对象的键值对
                                monthLines = Object.entries(item.month)
                                .map(([key, value]) => `--${key}月: ${value}`)
                                .join("\n");
                            }
                            // 返回每个对象的结果
                            return `${firstLine}\n${monthLines}`;
                        });
                        // 最终结果，用换行符连接每个对象的结果
                        response += results.join("\n\n");   
                    }
                    // 模拟逐字显示效果
                    that.simulateTyping(response);                    
                    // 请求成功, 页面展示 体质查询结果
                    that.setData({
                        respData: res.data.data,
                        predictResData: res.data.data.predict_res,
                        showRes: true,
                        year_end: res.data.data.year_end,
                        zodiac: res.data.data.zodiac,
                        month_day: res.data.data.month_day,
                        detail_time: res.data.data.detail_time,
                        // 展示中医诊断按钮, 隐藏看广告
                        medicine_btn: true,
                        handOver: true
                    });
                }
                return;
            }
        })        
    },
    //看广告免费咨询
    adShow: function (e) {
        let that = this;
        let cacheUserInfo = wx.getStorageSync('user_phone');
        let user_phone = (cacheUserInfo.phoneNumber && typeof (cacheUserInfo.phoneNumber) != 'undefined') ? cacheUserInfo.phoneNumber : '';
        let videoAd = null;

        videoAd = wx.createRewardedVideoAd({
            adUnitId: 'adunit-b35cfe40852d6b0f'
        })

        try {
            if (videoAd.closeHandler) {
                videoAd.offClose(videoAd.closeHandler);
                console.log("---videoAd.offClose 卸载成功---");
            }
        } catch (e) {
            console.log("---videoAd.offClose 卸载失败---");
            console.error(e);
        }

        videoAd.onLoad(() => {})
        videoAd.onError((err) => {
            console.error('激励视频光告加载失败', err)
        })
        videoAd.closeHandler = function (res) {
            // 用户点击了【关闭广告】按钮
            videoAd.offClose();
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发奖励
                if (!videoAd) return

                videoAd.offClose();
                // 正常播放结束，执行 体质查看结果
                console.log('广告结束---');
                // 观看广告完毕,进行预测
                that.gotoPredict();
                // wx.request({
                //     url: app.globalData.domain + 'v4/index/getTizhiSearch',
                //     method: 'POST',
                //     data: {
                //         user_phone: user_phone,
                //         type: 1,
                //         date: that.data.date,
                //         birthTime: that.data.birthTime,
                //         birthPlace: that.data.selectedOption
                //     },
                //     success: function (res) {
                //         console.log(res)
                //         if (res.data.code != 0) {
                //             wx.showModal({
                //                 title: '温馨提示',
                //                 showCancel: false,
                //                 content: res.data.msg
                //             })
                //             return;
                //         } else {
                //             // 请求成功, 页面展示 体质查询结果
                //             that.setData({
                //                 respData: res.data.data,
                //                 showRes: true,
                //                 year_end: res.data.data.year_end,
                //                 zodiac: res.data.data.zodiac,
                //                 month_day: res.data.data.month_day,
                //                 detail_time: res.data.data.detail_time,
                //                 // 展示中医诊断按钮, 隐藏看广告
                //                 medicine_btn: true
                //             });
                //         }
                //         return;
                //     }
                // })
            } else {
                //提前关闭小程序
            }
        };

        videoAd.onClose(videoAd.closeHandler);
        // 用户触发广告后，显示激励视频广告
        if (videoAd) {
            videoAd.show().catch(() => {
                // 失败重试
                videoAd.load()
                    .then(() => videoAd.show())
                    .catch(err => {
                        console.error('激励视频 广告显示失败', err)
                    })
            })
        }
    },
    onShareAppMessage() {
        let that = this;
        return {
            title: '天纪云.体质查询',
            path: '/pages/phySearch/index'
        }
    },
    onShareTimeline() {
        let that = this;
        return {
            title: '天纪云.体质查询',
            path: '/pages/menu/index'
        }
    },
    // AI输出效果控制
    simulateTyping(text) {
        let index = 0;
        const interval = setInterval(() => {
            if (index < text.length) {
                // 更新 AI 输出内容
                this.setData({
                    aiResponse: text.substring(0, index + 1)
                });
                // 自动滚动到页面底部
                wx.pageScrollTo({
                    scrollTop: 99999, // 设置一个足够大的值，确保滚动到底部
                    duration: 300 // 滚动动画时长，单位毫秒
                });
                index++;
            } else {
                clearInterval(interval);
            }
        }, 50); // 每50毫秒显示一个字
    }         
})